package com.fyyg.common.util;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;


/**
 * @author hang.ouyang
 * @date 2016-04-10 11:13
 */
public class SequenceGenerator {

    private static Integer machineNo = 1;
    private static ConcurrentHashMap<String, Integer> sequenceMap = new ConcurrentHashMap<String, Integer>();
    private static ConcurrentHashMap<String, Long> timeMap = new ConcurrentHashMap<String, Long>();
    private static DecimalFormat df = new DecimalFormat("00");
    private static SimpleDateFormat format = new SimpleDateFormat("yyMMddHHmmss");
    static {
        String machineEnv = System.getenv("fyyg.machine.no");
        if(machineEnv != null)
            machineNo = Integer.valueOf(machineEnv);
    }

    public static String get(String key) {
        synchronized (machineNo) {
            long curTime = timeGen();
            Long lastTime = timeMap.get(key);
            lastTime = lastTime == null ? 0 : lastTime;
            Integer sequence = sequenceMap.get(key);
            if (lastTime == curTime) {
                sequence = (sequence + 1);
                if (sequence == 0) {
                    curTime = tilNextMillis(lastTime);
                }
            } else {
                sequence = 0;
            }
            sequenceMap.put(key, sequence);
            timeMap.put(key, curTime);
            return String.format("%s%d%d%s", key, curTime, machineNo, df.format(sequence));
        }

    }

    protected static long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    protected static long timeGen() {
        return Long.valueOf(format.format(new Date()));
    }


    public static void main(String[] args) {
        System.out.println("ee\t"+System.currentTimeMillis());
        for (int i = 0; i <100 ; i++) {
            System.out.println( get("B"));
        }
        System.out.println("eee\t"+System.currentTimeMillis());
    }




}
